<?php
namespace Shake\Controller;
use Common\Controller\CommonController;

/**
 * 摇一摇模块
 */
class ShakeController extends CommonController {
	
	protected function _initialize(){
		parent::_initialize();
		$this->_mycache = S(C('REDIS_DSN'));
		$this->_auth();
		
		$this->_moduleid = 107;
		$this->_cust_location = new \Common\Model\CustLocationModel();
	}
    
    
    
	/**
	 * 摇一摇找用户
	 */
	public function shakeAction(){
		$longitude = I('request.longitude');
		$latitude = I('request.latitude');
		$this->_shake($longitude , $latitude);
	}
	
	private function _shake($longitude , $latitude){
		if(empty($longitude) || empty($latitude)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
		}
		
		$custid = 0;
		$timeStr = time();
		
		
		$expireTime = 300;
		//当前时刻
		$shakeKey = \cachekey::$key['BASE_KEY_CONF']['CUST_SHAKE'].$timeStr;
		$this->_mycache->expire($shakeKey , $expireTime);
		$this->_mycache->sadd($shakeKey,$this->_custInfo['custid']);
		$misNum = 0;
		while($misNum < 3){
			$custid = $this->_mycache->spop($shakeKey);
			if($custid == $this->_custInfo['custid']){
				$custid = 0;
				$this->_mycache->sadd($shakeKey,$this->_custInfo['custid']);
				$misNum++;
				sleep(2);
			}else{
				break;
			}
		}
		
		//前五分钟
		if(empty($custid)){
			for($tmpStr=($timeStr-$expireTime) ; $tmpStr<($timeStr+6) ; $tmpStr++){
				if($tmpStr == $timeStr) break;
				$shakeKey = \cachekey::$key['BASE_KEY_CONF']['CUST_SHAKE'].$tmpStr;
				$misNum = 0;
				while($misNum < 3){
					$custid = $this->_mycache->spop($shakeKey);
					if($custid == $this->_custInfo['custid']){
						$custid = 0;
						$this->_mycache->sadd($shakeKey,$this->_custInfo['custid']);
						$misNum++;
					}else{
						break;
					}
				}
				
				if(!empty($custid))break;
			}
			
		}
		
		
		if(empty($custid)){
			$this->status = 1701;
			$this->msg = L('STATUS_1701');
			$this->outPut();
		}
		
		$custInfo = $this->_getCustInfo($custid);
		if(empty($custInfo)){
			$this->status = 1701;
			$this->msg = L('STATUS_1701');
			$this->outPut();
		}
		
		$geohash = new \Geohash();
		$hash = $geohash->encode($latitude, $longitude);
		$this->_setLocation($latitude , $longitude , $hash);
		
		$location = $this->_cust_location->getCustLocation($custid);
		if(!empty($location)){
			$distance = \tools::getDistance($latitude, $longitude, $location['latitude'], $location['longitude']);
		}else{
			$this->status = 1701;
			$this->msg = L('STATUS_1701');
			$this->outPut();
		}
		
		$returnData = array();
		$returnData['custid'] = $custInfo['custid'];
		$returnData['nickname'] = $custInfo['nickname'];
		$returnData['sex'] = $custInfo['sex'];
		$returnData['distance'] = (string)$distance;
		$this->data = $returnData;
		$this->outPut();
	}
    
    
}
